package com.duolebo.uteped_sdk.model;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.provider.BaseColumns;

import com.duolebo.uteped_sdk.db.IRecord;

import java.util.ArrayList;

/**
 * @Author: LiuYang
 * @Date: 2023/12/20 11:54
 * @Description:
 */
public abstract class BaseModel implements IRecord {

    private long pkId = NO_PKID;
    private long dateCreated = 0L;
    private long dateModified = 0L;
    private boolean isModifying = false;

    private String address;

    BaseModel(){}

    /**
     * BaseModel
     * @param model model
     */
    BaseModel(BaseModel model) {
        pkId = model.pkId;
        dateCreated = model.dateCreated;
        dateModified = model.dateCreated;
        address = model.address;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public long getPKIdValue() {
        return pkId;
    }

    @Override
    public String getPKIdKey() {
        return Fields._ID;
    }

    @Override
    public void onModifyFieldValues() {
        isModifying = true;
    }

    @Override
    public void writeFieldValues(ContentValues values) {
        // don't update pkId, as it'd be updated automatically.
        if (!isModifying) {
            // create new record.
            dateCreated = System.currentTimeMillis();
            values.put(Fields.DATE_CREATED, dateCreated);
            dateModified = dateCreated;
            values.put(Fields.DATE_MODIFIED, dateModified);
        } else {
            // update existing record.
            dateModified = System.currentTimeMillis();
            values.put(Fields.DATE_MODIFIED, dateModified);
            isModifying = false;
        }

        values.put(Fields.ADDRESS, address);
    }

    @SuppressLint("Range")
    @Override
    public void readFieldValues(Cursor c) {
        pkId = c.getLong(c.getColumnIndex(getPKIdKey()));
        dateCreated = c.getLong(c.getColumnIndex(Fields.DATE_CREATED));
        dateModified = c.getLong(c.getColumnIndex(Fields.DATE_MODIFIED));
        address = c.getString(c.getColumnIndex(Fields.ADDRESS));
    }

    @Override
    public void prepareFieldDefs(ArrayList<String> fieldDefs) {
        fieldDefs.add(getPKIdKey() + FIELD_TYPE_PRIMARY);
        fieldDefs.add(Fields.DATE_CREATED + FIELD_TYPE_NUMERIC);
        fieldDefs.add(Fields.DATE_MODIFIED + FIELD_TYPE_NUMERIC);
        fieldDefs.add(Fields.ADDRESS + FIELD_TYPE_TEXT);
    }

    public interface Fields extends BaseColumns { //NOSONAR
        String DATE_CREATED = "date_created";
        String DATE_MODIFIED = "date_modified";
        String ADDRESS = "address";
    }
}
